﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using FacebookAcessLibrary.FacebookClass;
using GiveGraphMappers;
using GiveGraphModel;
using Microsoft.IdentityModel.Claims;
using WebApp.Util;

namespace WebApp.Controllers
{
    public class ServiceController : Controller
    {
        //
        // GET: /Service/

        public ActionResult Index()
        {
            return View("ServiceDetails", new Service());
        }

        public ActionResult AddRequest()
        {
            return View("AddServiceRequest");
        }

        public ActionResult AddServiceRequest(Schedule[] schedule, string[] typesOfVolunteering, string[] destinataries, string[] areasOfVolunteering)
        {
            var not = new Notification();
            var serviceRequestMapper = new ServiceRequestMapper();
            var organizationMapper = new OrganizationMapper();
            var usrId = ((IClaimsIdentity)User.Identity).GetUserId();
            var organization = organizationMapper.Get(usrId);
            
            if(areasOfVolunteering != null)
            {
                foreach (string areaOfVolunteering in areasOfVolunteering)
                {
                    ServiceRequest request = new ServiceRequest();

                    var serviceCategoryMapper = new ServiceCategoryMapper();

                    string volunteering = areaOfVolunteering;

                    request.Category = serviceCategoryMapper
                        .GetAll()
                        .Where(scm => scm.Name == volunteering)
                        .First();

                    request.Organization = organization;
                    
                    if (destinataries != null)
                    {
                        var specialtyAreaMapper = new SpecialtyAreaMapper();
                        request.SpecialtyAreas = new List<SpecialtyArea>(
                                                                    destinataries
                                                                        .Select(
                                                                            s => specialtyAreaMapper
                                                                                     .GetAll()
                                                                                   .Where(sa => sa.Name == s).First()
                                                                          )
                                                                       );
                        request.SpecialtyAreas.Each(s => specialtyAreaMapper.Attach(s));
                    }

                    if (typesOfVolunteering != null)
                        request.TypeOfVolunteering = new List<string>(typesOfVolunteering);

                    request.Organization.Requests.Add(request);
                    serviceRequestMapper.Add(request);
                }
            }

            serviceRequestMapper.ForceSave();
            /// to late to think
            TempData["ServiceSearch"] = areasOfVolunteering;
            return RedirectToAction("Services", "Search", new { organization = organization.MemberId });
        }

        public ActionResult RequestService(int resourceid)
        {
            JsonResult result = new JsonResult();
            result.Data = "";

            return result;
        }

        public ActionResult RespondServiceRequest(int requestId)
        {
            return View(new ServiceRequestMapper().Get(requestId));
        }

        public ActionResult AcceptRequest(int requestId)
        {
            ServiceRequestMapper serviceRequestMapper = new ServiceRequestMapper();
            ServiceResponseMapper serviceResponseMapper = new ServiceResponseMapper();
            ServiceMapper serviceMapper = new ServiceMapper();
            UserMapper userMapper = new UserMapper(); ;

            User user = userMapper.Get(((IClaimsIdentity)User.Identity).GetUserId());

            serviceResponseMapper.Add(new ServiceResponse
                                          {
                                              Request = serviceRequestMapper.Get(requestId),
                                              Service = serviceMapper.GetByUser(user.MemberId),
                                              User = user
                                          });
            Response.Redirect("/Profile");
            return null;
        }

        public ActionResult RejectRequest(int requestId)
        {
            Response.Redirect("/Profile");
            return null;
        }

        [HttpPost]
        public JsonResult UpdateServices(Schedule[] schedule, string[] typesOfVolunteering, string[] destinataries, string[] areasOfVolunteering)
        {
            var serviceMapper = new ServiceMapper();
            var usrId = ((IClaimsIdentity)User.Identity).GetUserId();
            
            var service = serviceMapper.GetByUser(usrId);
            if(service != null)
                serviceMapper.Delete(service);

            service = new Service{Description = ""};
            var usr = new UserMapper().Get(usrId);
            usr.Provides = new List<Resource>() {service};
            service.ProviderMember = usr;
            serviceMapper.ForceSave();

            serviceMapper.Attach(service);
            
            if (schedule != null) { 
                service.Schedule = new List<Schedule>(schedule);
                service.Schedule.Each(s=>serviceMapper.GetContext().Entry(s).State = EntityState.Added );
            }
            if (typesOfVolunteering != null)
                service.TypeOfVolunteering = new List<string>(typesOfVolunteering);

            if(destinataries != null)
            {
                var specialtyAreaMapper = new SpecialtyAreaMapper();
                service.SpecialtyAreas = new List<SpecialtyArea>(
                                                            destinataries
                                                                .Select(
                                                                    s => specialtyAreaMapper
                                                                             .GetAll()
                                                                           .Where(sa => sa.Name == s).First()
                                                                  )
                                                               );
                service.SpecialtyAreas.Each(s=>specialtyAreaMapper.Attach(s));
            }

            if (areasOfVolunteering != null)
            {
                var serviceCategoryMapper = new ServiceCategoryMapper();

                service.Categories = new List<ServiceCategory>(areasOfVolunteering.Select(
                    s => serviceCategoryMapper
                             .GetAll()
                             .Where(scm => scm.Name == s)
                             .First()
                                                               ));
                service.Categories.Each(c => serviceCategoryMapper.Attach(c));
            }
            
            
            serviceMapper.ForceSave();

            
            /*
            var service = serviceMapper.GetByUser(usrId) ??
                      new Service
                          {
                              Categories = new List<ServiceCategory>(),
                              SpecialtyAreas = new List<SpecialtyArea>(),
                              Schedule = new List<Schedule>(),
                              TypeOfVolunteering = new List<String>()
                          };

            schedule.Where(sch => service.Schedule.All(s => s.ScheduleId != sch.ScheduleId))
                    .Each(service.Schedule.Add);

            var serviceCategoryMapper = new ServiceCategoryMapper();

            areasOfVolunteering.Select(
                                    s => serviceCategoryMapper
                                                .GetAll()
                                                .Where(scm => scm.Name == s)
                                                .First()
                                      )
                               .Except(service.Categories)
                               .Each(service.Categories.Add);

            typesOfVolunteering
                        .Except(service.TypeOfVolunteering)
                        .Each(service.TypeOfVolunteering.Add);

            var specialtyAreaMapper = new SpecialtyAreaMapper();

            destinataries.Select(
                                    s=>specialtyAreaMapper.GetAll().Where(sa=>sa.Name == s).First()
                                )
                         .Except(service.SpecialtyAreas)
                         .Each(service.SpecialtyAreas.Add);

            serviceMapper.Update(service);
            )*/
            /// to late to think
            return Json("Services Updated");
        }


    }

    public static class Extensions
    {
        public static void Each<T>(this IEnumerable<T> _this, Action<T> action)
        {
            foreach (var s in _this)
            {
                action(s);
            }
        }
    }
}
